<route lang="json5">
{
  style: {
    navigationBarTitleText: '找回密码',
  },
}
</route>

<template>
  <view class="forgot-password-container">
    <view class="steps-container">
      <wd-steps :active="currentStep">
        <wd-step title="验证手机" />
        <wd-step title="重置密码" />
        <wd-step title="完成" />
      </wd-steps>
    </view>

    <!-- 步骤一：验证手机号 -->
    <view v-if="currentStep === 0" class="form-container">
      <wd-cell-group>
        <!-- 手机号输入 -->
        <wd-input
          v-model="form.phone"
          label="手机号"
          placeholder="请输入手机号"
          type="number"
          maxlength="11"
          :error="errors.phone"
          :error-message="errors.phoneMessage"
          @blur="validatePhone"
        >
          <template #prefix>
            <text class="iconfont icon-phone"></text>
          </template>
        </wd-input>

        <!-- 验证码输入 -->
        <wd-input
          v-model="form.code"
          label="验证码"
          placeholder="请输入验证码"
          type="number"
          maxlength="6"
          :error="errors.code"
          :error-message="errors.codeMessage"
          @blur="validateCode"
        >
          <template #prefix>
            <text class="iconfont icon-shield"></text>
          </template>
          <template #suffix>
            <wd-button
              size="small"
              :disabled="!!countdown || !form.phone || errors.phone"
              @click="handleSendCode"
            >
              {{ countdown ? `${countdown}s后重新获取` : '获取验证码' }}
            </wd-button>
          </template>
        </wd-input>
      </wd-cell-group>

      <view class="button-container">
        <wd-button type="primary" block @click="handleVerifyPhone" :loading="loading">
          下一步
        </wd-button>
      </view>
    </view>

    <!-- 步骤二：重置密码 -->
    <view v-if="currentStep === 1" class="form-container">
      <wd-cell-group>
        <!-- 新密码输入 -->
        <wd-input
          v-model="form.password"
          label="新密码"
          placeholder="请输入新密码"
          :type="showPassword ? 'text' : 'password'"
          :error="errors.password"
          :error-message="errors.passwordMessage"
          @blur="validatePassword"
        >
          <template #prefix>
            <text class="iconfont icon-lock"></text>
          </template>
          <template #suffix>
            <text
              class="iconfont"
              :class="showPassword ? 'icon-eye' : 'icon-eye-close'"
              @click="togglePasswordVisibility"
            ></text>
          </template>
        </wd-input>

        <!-- 确认新密码 -->
        <wd-input
          v-model="form.confirmPassword"
          label="确认密码"
          placeholder="请再次输入新密码"
          :type="showConfirmPassword ? 'text' : 'password'"
          :error="errors.confirmPassword"
          :error-message="errors.confirmPasswordMessage"
          @blur="validateConfirmPassword"
        >
          <template #prefix>
            <text class="iconfont icon-lock"></text>
          </template>
          <template #suffix>
            <text
              class="iconfont"
              :class="showConfirmPassword ? 'icon-eye' : 'icon-eye-close'"
              @click="toggleConfirmPasswordVisibility"
            ></text>
          </template>
        </wd-input>
      </wd-cell-group>

      <view class="button-container">
        <wd-button type="primary" block @click="handleResetPassword" :loading="loading">
          确认修改
        </wd-button>
      </view>
    </view>

    <!-- 步骤三：完成 -->
    <view v-if="currentStep === 2" class="success-container">
      <view class="success-icon">
        <text class="iconfont icon-success"></text>
      </view>
      <view class="success-title">密码重置成功</view>
      <view class="success-desc">请使用新密码登录</view>
      <view class="button-container">
        <wd-button type="primary" block @click="navigateToLogin">
          返回登录
        </wd-button>
      </view>
    </view>
  </view>
</template>

<script lang="ts" setup>
import { ref, reactive, onUnmounted } from 'vue'
import { showToast } from '@/utils/toast'
import { sendCode, resetPassword } from '@/api/auth'

const currentStep = ref(0)
const form = reactive({
  phone: '',
  code: '',
  password: '',
  confirmPassword: '',
})

const errors = reactive({
  phone: false,
  phoneMessage: '',
  code: false,
  codeMessage: '',
  password: false,
  passwordMessage: '',
  confirmPassword: false,
  confirmPasswordMessage: '',
})

const loading = ref(false)
const showPassword = ref(false)
const showConfirmPassword = ref(false)
const countdown = ref(0)
let countdownTimer: number | null = null

// 表单验证
const validatePhone = () => {
  const phoneRegex = /^1[3-9]\d{9}$/
  if (!form.phone) {
    errors.phone = true
    errors.phoneMessage = '请输入手机号'
    return false
  }
  if (!phoneRegex.test(form.phone)) {
    errors.phone = true
    errors.phoneMessage = '请输入正确的手机号'
    return false
  }
  errors.phone = false
  errors.phoneMessage = ''
  return true
}

const validateCode = () => {
  if (!form.code) {
    errors.code = true
    errors.codeMessage = '请输入验证码'
    return false
  }
  if (form.code.length !== 6) {
    errors.code = true
    errors.codeMessage = '验证码长度不正确'
    return false
  }
  errors.code = false
  errors.codeMessage = ''
  return true
}

const validatePassword = () => {
  if (!form.password) {
    errors.password = true
    errors.passwordMessage = '请输入新密码'
    return false
  }
  if (form.password.length < 6) {
    errors.password = true
    errors.passwordMessage = '密码长度不能小于6位'
    return false
  }
  errors.password = false
  errors.passwordMessage = ''
  return true
}

const validateConfirmPassword = () => {
  if (!form.confirmPassword) {
    errors.confirmPassword = true
    errors.confirmPasswordMessage = '请再次输入新密码'
    return false
  }
  if (form.confirmPassword !== form.password) {
    errors.confirmPassword = true
    errors.confirmPasswordMessage = '两次输入的密码不一致'
    return false
  }
  errors.confirmPassword = false
  errors.confirmPasswordMessage = ''
  return true
}

// 发送验证码
const handleSendCode = async () => {
  if (!validatePhone()) {
    return
  }

  try {
    loading.value = true
    await sendCode({
      phone: form.phone,
      type: 'reset'
    })
    showToast('验证码发送成功')
    startCountdown()
  } catch (error) {
    showToast(error.message || '验证码发送失败，请重试')
  } finally {
    loading.value = false
  }
}

// 开始倒计时
const startCountdown = () => {
  countdown.value = 60
  countdownTimer = setInterval(() => {
    if (countdown.value > 0) {
      countdown.value--
    } else {
      clearInterval(countdownTimer!)
      countdownTimer = null
    }
  }, 1000)
}

// 验证手机号
const handleVerifyPhone = async () => {
  if (!validatePhone() || !validateCode()) {
    return
  }

  loading.value = true
  try {
    // 这里只需验证手机号和验证码是否正确
    // 实际的密码重置会在下一步进行
    currentStep.value = 1
  } catch (error) {
    showToast(error.message || '验证失败，请重试')
  } finally {
    loading.value = false
  }
}

// 重置密码
const handleResetPassword = async () => {
  if (!validatePassword() || !validateConfirmPassword()) {
    return
  }

  loading.value = true
  try {
    await resetPassword({
      phone: form.phone,
      code: form.code,
      password: form.password,
      confirmPassword: form.confirmPassword
    })
    
    currentStep.value = 2
  } catch (error) {
    showToast(error.message || '密码重置失败，请重试')
  } finally {
    loading.value = false
  }
}

// 切换密码可见性
const togglePasswordVisibility = () => {
  showPassword.value = !showPassword.value
}

const toggleConfirmPasswordVisibility = () => {
  showConfirmPassword.value = !showConfirmPassword.value
}

// 返回登录页
const navigateToLogin = () => {
  uni.redirectTo({
    url: '/pages/login/index',
  })
}

// 组件销毁时清理倒计时
onUnmounted(() => {
  if (countdownTimer) {
    clearInterval(countdownTimer)
  }
})
</script>

<style lang="scss">
.forgot-password-container {
  min-height: 100vh;
  padding: 20px;
  background-color: #fff;
}

.steps-container {
  margin: 20px 0 40px;
}

.form-container {
  margin-top: 20px;
}

.button-container {
  margin: 40px 0 20px;
}

.success-container {
  display: flex;
  flex-direction: column;
  align-items: center;
  padding: 60px 0;

  .success-icon {
    font-size: 80px;
    color: #67c23a;
    margin-bottom: 20px;

    .iconfont {
      font-size: inherit;
    }
  }

  .success-title {
    font-size: 24px;
    font-weight: bold;
    color: #333;
    margin-bottom: 12px;
  }

  .success-desc {
    font-size: 14px;
    color: #666;
    margin-bottom: 40px;
  }
}
</style>
